import { batch } from 'solid-js';
import { createMutable } from 'solid-js/store';

export class EditorModel {
  private document!: Document;
  public state = createMutable({
    canUndo: false,
    canRedo: false,
    bold: false,
    italic: false,
    strikeThrough: false,
    underLine: false,
    justifyLeft: false,
    justifyCenter: false,
    justifyRight: false,
  });

  public constructor(document?: Document) {
    if (document) {
      this.setDocument(document);
    }
  }

  public setDocument(document: Document) {
    if (this.document) {
      this.document.removeEventListener('selectionchange', this.onSelectionChange);
    }
    this.document = document;
    this.document.addEventListener('selectionchange', this.onSelectionChange);
    return this;
  }

  private run(commandId: string, showUI: boolean = false, value?: string) {
    const res = this.document.execCommand(commandId, showUI, value);
    this.onSelectionChange();
    return res;
  }

  private queryState(commandId: string) {
    return this.document.queryCommandState(commandId);
  }

  private queryEnable(commandId: string) {
    return this.document.queryCommandEnabled(commandId);
  }

  // 撤销
  public undo() {
    this.run('undo');
    return this;
  }
  // 重做
  public redo() {
    this.run('redo');
    return this;
  }

  // 加粗
  public bold() {
    this.run('bold');
    return this;
  }
  // 斜体
  public italic() {
    this.run('italic');
    return this;
  }

  // 删除线
  public strikeThrough() {
    this.run('strikeThrough');
    return this;
  }

  // 下划线
  public underLine() {
    this.run('underLine');
    return this;
  }

  // 居左
  public justifyLeft() {
    this.run('JustifyLeft');
  }
  // 居中
  public justifyCenter(): void {
    this.run('justifyCenter');
  }
  // 居右
  public justifyRight(): void {
    this.run('justifyRight');
    this.document
  }

  // 选择事件
  public onSelectionChange = () => {
    batch(() => {
      this.state.canUndo = this.queryEnable('undo');
      this.state.canRedo = this.queryEnable('redo');
      this.state.bold = this.queryState('bold');
      this.state.italic = this.queryState('italic');
      this.state.underLine = this.queryState('underLine');
      this.state.strikeThrough = this.queryState('strikeThrough');
      this.state.justifyLeft = this.queryState('justifyLeft');
      this.state.justifyCenter = this.queryState('justifyCenter');
      this.state.justifyRight = this.queryState('justifyRight');
    });
  };
}
